package com.dld.protocol.json;

import java.io.ByteArrayInputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

import com.baidu.mapapi.c;
import com.dld.android.util.LogUtils;
import com.dld.coupon.view.DownloadListView;
import com.dld.protocol.json.Protocol.OnJsonProtocolResult;

public class AroundResponse extends OnJsonProtocolResult {

	private Handler postHandler;
	private DownloadListView list;
	private int download_flag;

	public AroundResponse(Class<?> paramClass, Handler h,
			DownloadListView paramlist, int flag) {
		super(paramClass);
		this.postHandler = h;
		this.list = paramlist;
		this.download_flag = flag;
	}

	@Override
	public void onException(String paramString, Exception paramException) {
		LogUtils.log("", "param object ************   "
				+ paramException.toString());
	}

	private void sendExceptionMsg() {
		Message m = Message.obtain();
		m.what = 0;
		m.obj = this.list;
		postHandler.sendMessage(m);
	}

	@Override
	public void onResult(String paramString, Object paramObject) {

		if (paramObject == null) {
			sendExceptionMsg();
			return;
		}
		String content = (String) paramObject;
		try {
			Element root = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder().parse(
							new ByteArrayInputStream(content.getBytes()))
					.getDocumentElement();
			NodeList lsittotal = root.getElementsByTagName("total");
			String total = lsittotal.item(0).getFirstChild().getNodeValue();
			List<CouponDetail> list = CouponDetail.fromXmlToAdroundInfo(root);
			Message m = Message.obtain();
			m.what = 0xff;
			m.arg1 = Integer.parseInt(total);
			m.obj = list;
			m.arg2 = this.download_flag;
			postHandler.sendMessage(m);
		} catch (Exception e) {
			e.printStackTrace();
			sendExceptionMsg();
		}
	}

}
